package cn.itsource.service.impl;

import cn.hutool.http.HttpUtil;
import cn.itsource.domain.Login;
import cn.itsource.dto.LoginMealDto;
import cn.itsource.mapper.LoginMapper;
import cn.itsource.result.JSONResult;
import cn.itsource.service.ILoginService;
import cn.itsource.vo.JwtVo;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 * 登录表 服务实现类
 * </p>
 *
 * @author fengluochen
 * @since 2022-11-09
 */
@Service
public class LoginServiceImpl extends ServiceImpl<LoginMapper, Login> implements ILoginService {
    @Resource
    private LoginMapper loginMapper;
    @Override
    public JSONResult saveLoginMeal(LoginMealDto meal) {
        loginMapper.saveLoginMeal(meal);
        return JSONResult.success();
    }

    @Override
    public JSONResult user(Login login) {
        /*
        * 1、发请求获取JWT：http://localhost:1050/oauth/token?client_id=admin&client_secret=123456&grant_type=password&redirect_uri=http://www.baidu.com&username=zs&password=123456
        * 2.获取返回对象
        * 3.将返回对象全部返回前端
        * */
        String url="http://localhost:1050/oauth/token?client_id=admin&client_secret=123456&grant_type=password&redirect_uri=http://www.baidu.com&username=%s&password=%s";
        url= String.format(url, login.getUsername(), login.getPassword());
        //发请求
        String result = HttpUtil.post(url,"");
        //转换为vo对象
        JwtVo jwtVo = JSONObject.parseObject(result, JwtVo.class);
        return JSONResult.success(jwtVo);
    }

    @Override
    public JwtVo refreshToken(String refreshToken) {
        String url = "http://localhost:1050/oauth/token?grant_type=refresh_token&refresh_token=%s&client_id=admin&client_secret=123456";
        url = String.format(url, refreshToken);
        //发请求
        String result = HttpUtil.post(url, "");
        //字符串转对象
        JwtVo jwtVo = JSONObject.parseObject(result, JwtVo.class);
        return jwtVo;
    }
}
